﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace MDX_Studio_v2
{
	class PerfCounter
	{
		private PerformanceCounter _counter;
		private string _description;
		private int _value;

		public string Description { get { return _description; } }
		public int Value { get{ return _value; } }

		public PerfCounter(string serverName, string version, string category, string name, string description)
		{
			try
			{
				string str2;
				_counter = new PerformanceCounter();

				string[] strArray = serverName.Split(new char[] { '\\' });

				if ((strArray.Length > 2) || (strArray.Length < 1))
				{
					throw new Exception("Invalid server name");
				}

				string machineName = strArray[0];
				if ((machineName.Equals(".") || machineName.Equals("local")) || machineName.Equals("localhost"))
				{
					machineName = Environment.MachineName;
				}

				_counter.MachineName = machineName;
				if (1 == strArray.Length)
				{
					str2 = string.Format("MSAS {0}:{1}", version, category);
				}
				else
				{
					str2 = string.Format("MSOLAP${0}:{1}", strArray[1], category);
				}

				_counter.CategoryName = str2;
				_counter.CounterName = name;
				_description = description;
				_counter.NextValue();
			}
			catch(Exception ex)
			{
				_counter = null;
				Console.WriteLine("PerfCounter.cs\\Constructor: " + ex.Message);
			}
		}

		public void Finish()
		{
			try
			{
				if (_counter != null)
				{
					_value = ((int)_counter.NextValue()) - _value;
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine("PerfCounter.cs\\Finish: " + ex.Message);
			}
		}

		public string GetValueText()
		{
			if (_value != -1)
			{
				return _value.ToString();
			}
			return "?";
		}

		public void Start()
		{
			try
			{
				if (_counter != null)
				{
					_value = (int)_counter.NextValue();
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine("PerfCounter.cs\\Start: " + ex.Message);
			}
		}
	}
}
